
//
//  CourseBannerView.m
//  ShowYork
//
//  Created by hxh on 2020/8/28.
//  Copyright © 2020 hxh. All rights reserved.
//

#import "LessonBannerView.h"
#import "LessonBannerModel.h"
#import "XHPageControl.h"
#import <Accelerate/Accelerate.h>
@interface LessonBannerView ()<SDCycleScrollViewDelegate>
@property (nonatomic,strong)SDCycleScrollView *scrollView;
@property (nonatomic,strong)XHPageControl *page;
@property (nonatomic,strong)NSMutableArray *colors;

@property (nonatomic,assign)NSInteger currentIndex;


@end

@implementation LessonBannerView

- (NSMutableArray *)colors{
    if (!_colors) {
        _colors = [NSMutableArray array];
    }
    return _colors;
}

- (instancetype)init{
    if (self = [super init]) {
        [self setUI];
    }
    return self;
}

- (void)setAdjustWhenControllerViewWillAppera{
    [self.scrollView adjustWhenControllerViewWillAppera];
}
- (void)setUI{

    self.frame = CGRectMake(0, 0, kScreenW,kScreenW * 0.4);
    
    self.backgroundColor = [UIColor clearColor];
    
    self.scrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(16,16, kScreenW - 32, kScreenW * 0.4 - 16) delegate:self placeholderImage:[UIImage imageNamed:@""]];
    self.scrollView.autoScrollTimeInterval = 3;
    self.scrollView.bannerImageViewContentMode = UIViewContentModeScaleAspectFill;
    self.scrollView.backgroundColor = RGBA(221, 221, 221, 1);
    self.scrollView.showPageControl = NO;
    self.scrollView.layer.cornerRadius = 8;
    self.scrollView.layer.masksToBounds = YES;
    [self addSubview:self.scrollView];
    
    self.page = [[XHPageControl alloc]initWithFrame:CGRectMake(0, self.cl_height - 30, kScreenW, 30)];
    self.page.numberOfPages = 5;
    self.page.currentPage = 0;
    self.page.currentMultiple = 1;
    self.page.controlSize = 6;
    self.page.currentColor = [UIColor whiteColor];
    self.page.hidden = YES;
    //self.page.currentBkImg = [UIImage imageNamed:@"zl_btn_selected"];
  //  self.page.delegate = self;
    [self addSubview:self.page];
        
}


- (void)setBanners:(NSMutableArray *)banners{
  
    _banners = banners;
    if (banners.count == 0) {
        return;
    }
    
    if (banners.count == 1) {
        self.scrollView.autoScroll = NO;
    }else{
        self.scrollView.autoScroll = YES;
    }
    
    NSMutableArray *urls = [NSMutableArray array];
    
    [self.colors removeAllObjects];

    
    [banners enumerateObjectsUsingBlock:^(LessonBannerModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
    
        [self.colors addObject:[UIColor clearColor]];
            
        [urls addObject:obj.image];
        
//        [[SDWebImageManager sharedManager] loadImageWithURL:[NSURL URLWithString:obj.image] options:0 progress:^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL) {
//
//        } completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) {
//            if (finished) {
//                UIColor *color = [self mostColor:image];
//                [self.colors replaceObjectAtIndex:idx withObject:color];
//            }
//
//            if (self.colors.count == banners.count) {
//
//
//
//                if (self.delegate && [self.delegate respondsToSelector:@selector(updateHomePageNavColor:)]) {
//                    [self.delegate updateHomePageNavColor:[self.colors firstObject]];
//                }
//
//            }
//
//        }];
    }];
    self.scrollView.imageURLStringsGroup = urls;
  
    self.page.numberOfPages = banners.count;
    self.page.hidden = banners.count <= 1;
    
}


//- (void)updateContainViewLayer{
//    NSMutableArray *layers = [NSMutableArray array];
//
//    for (CALayer *layer in self.layer.sublayers) {
//        if ([layer isKindOfClass:[CAGradientLayer class]]) {
//            [layers addObject:layer];
//        }
//    }
//    [layers makeObjectsPerformSelector:@selector(removeFromSuperlayer)];
//    NSInteger index = self.scrollView.contentOffset.x/kScreenW;
//    UIImageView *imgV = self.imgViewArr[index];
//    UIColor *color = [self mostColor:imgV.image];
//
//    CAGradientLayer *layer = [CAGradientLayer new];
//    layer.colors = @[(__bridge id)[UIColor whiteColor].CGColor, (__bridge id)color.CGColor];
//    layer.startPoint = CGPointMake(1, 1);
//    layer.endPoint = CGPointMake(1, 0);
//    layer.frame = self.bounds;
//    [self.layer insertSublayer:layer atIndex:0];
//}


//根据图片获取图片的主色调
- (UIColor*)mostColor:(UIImage*)image{
    
#if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_6_1
    int bitmapInfo = kCGBitmapByteOrderDefault | kCGImageAlphaPremultipliedLast;
#else
    int bitmapInfo = kCGImageAlphaPremultipliedLast;
#endif
    //第一步 先把图片缩小 加快计算速度. 但越小结果误差可能越大
    CGSize thumbSize=CGSizeMake(50, 50);
    
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef context = CGBitmapContextCreate(NULL,
                                                 thumbSize.width,
                                                 thumbSize.height,
                                                 8,//bits per component
                                                 thumbSize.width*4,
                                                 colorSpace,
                                                 bitmapInfo);
    
    CGRect drawRect = CGRectMake(0, 0, thumbSize.width, thumbSize.height);
    CGContextDrawImage(context, drawRect, image.CGImage);
    CGColorSpaceRelease(colorSpace);
    
    //第二步 取每个点的像素值
    unsigned char* data = CGBitmapContextGetData (context);
    if (data == NULL) return nil;
    NSCountedSet *cls=[NSCountedSet setWithCapacity:thumbSize.width*thumbSize.height];
    
    for (int x=0; x<thumbSize.width; x++) {
        for (int y=0; y<thumbSize.height; y++) {
            int offset = 4*(x*y);
            int red = data[offset];
            int green = data[offset+1];
            int blue = data[offset+2];
            int alpha =  data[offset+3];
            if (alpha>0) {//去除透明
                if (red==255&&green==255&&blue==255) {//去除白色
                }else{
                    NSArray *clr=@[@(red),@(green),@(blue),@(alpha)];
                    [cls addObject:clr];
                }
                
            }
        }
    }
    CGContextRelease(context);
    //第三步 找到出现次数最多的那个颜色
    NSEnumerator *enumerator = [cls objectEnumerator];
    NSArray *curColor = nil;
    NSArray *MaxColor=nil;
    NSUInteger MaxCount=0;
    while ( (curColor = [enumerator nextObject]) != nil )
    {
        NSUInteger tmpCount = [cls countForObject:curColor];
        if ( tmpCount < MaxCount ) continue;
        MaxCount=tmpCount;
        MaxColor=curColor;
        
    }
    return [UIColor colorWithRed:([MaxColor[0] intValue]/255.0f) green:([MaxColor[1] intValue]/255.0f) blue:([MaxColor[2] intValue]/255.0f) alpha:([MaxColor[3] intValue]/255.0f)];
}


//#pragma mark - 手势
//- (void)tapMethod{
//    NSInteger index = self.scrollView.contentOffset.x/kScreenW;

//}

/** 点击图片回调 */
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index{
    if (self.delegate && [self.delegate respondsToSelector:@selector(didSelectAtIndex:)]) {
        [self.delegate didSelectAtIndex:index];
    }
}

/** 图片滚动回调 */
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didScrollToIndex:(NSInteger)index{
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(updateHomePageNavColor:)] && index < self.colors.count) {
        [self.delegate updateHomePageNavColor:self.colors[index]];
    }
    self.currentIndex = index;
    
    self.page.currentPage = index;
}




@end
